package com.doctcloud.common.core.exception;

import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowException;
import com.alibaba.csp.sentinel.slots.system.SystemBlockException;
import com.alibaba.fastjson2.JSON;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

import static com.doctcloud.common.core.constant.HttpStatus.SUCCESS;
import static com.doctcloud.common.core.constant.SentinelStatus.*;

public class BlockExceptionHandler implements com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler {
    @Override
    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, BlockException e) throws Exception {
        Map<String,Object> info = new HashMap<>();
        if (e instanceof FlowException){
            info.put("code",LIMIT);
            info.put("mag","熔断服务-限流异常");
        } else if (e instanceof DegradeException) {
            info.put("code",DEGRADE);
            info.put("msg","熔断服务-降级异常");
        } else if (e instanceof ParamFlowException){
            info.put("code",PARAM);
            info.put("msg","熔断服务-热点参数异常");
        } else if (e instanceof SystemBlockException){
            info.put("code",SYSTEM);
            info.put("msg","熔断服务-系统规则异常");
        } else if (e instanceof AuthorityException) {
            info.put("code",AUTHORITY);
            info.put("msg","熔断服务-认证异常");
        }
        //设置JSON返回
        httpServletResponse.setStatus(SUCCESS);
        httpServletResponse.setHeader("content-type","application/json;charset=UTF-8");
        httpServletResponse.getWriter().write(JSON.toJSONString(info));
    }
}
